<template>
  <div class="canvas-box" v-for="i in 60" :key="i">
    {{ i }}号canvas
    <canvas :id="'test-canvas' + i" width="280" height="280"></canvas>
  </div>
</template>

<script setup lang="ts">
  import testWorker from './test.worker?worker';
  import { onMounted } from 'vue';
  import { saveImageToLocal } from '@/utils/ipcRenderer';

  onMounted(() => {
    for (let i = 1; i <= 60; i++) {
      const canvas: any = document.getElementById('test-canvas' + i);
      const canvasWorker: any = canvas.transferControlToOffscreen();
      const worker = new testWorker();
      worker.onmessage = (e) => {
        try {
          const {
            data: { command, data },
          } = e;
          console.log(data);
          switch (command) {
            case 'draw':
              let c1: any = document.createElement('canvas');
              c1.width = 280;
              c1.height = 280;
              let c1Ctx: any = c1.getContext('2d');
              // console.log(data.image);
              c1Ctx.putImageData(data.image, 0, 0);
              console.log(c1.toDataURL());
              // saveImageToLocal(`cs-${Date.now()}.webp`, data.image);
              saveImageToLocal(`cs-${Date.now()}.webp`, c1.toDataURL());
              // console.log(canvas.transferToImageBitmap());
              break;
          }
        } catch (e) {
          console.log(e);
        }
      };
      //控制权转让
      worker.postMessage(
        {
          command: 'init',
          data: {
            canvas: canvasWorker,
            index: i,
          },
        },
        [canvasWorker]
      );
    }
  });
</script>

<style scoped lang="less">
  .canvas-box {
    display: inline-block;
    font-size: 24px;
  }
</style>
